<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    > 
      <template slot-scope="scope" slot="menu">
        <el-button
          v-if="permissionList.viewBtn"
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleDetail(scope.row)"
          >详 情</el-button
        >
      </template>
      <template slot="menuRight">
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page ref="searchRpiSelect" label="rpiName" value="rpiNo" :select.sync="search.rpiNo" :url="website.searchLink.merchantUrl" placeholder-text="商户" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="groupRpiNoSearch">
        <select-page ref="searchRpsSelect" label="rpiName" value="rpiNo" :select.sync="search.groupRpiNo" :url="website.searchLink.groupUrl" placeholder-text="集团商户" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{disabled,size}" slot="beginTimeSearch">
        <el-date-picker v-model="search.beginTime" type="datetime" :editable="false" :clearable="false" value-format='yyyy-MM-dd HH:mm:ss' @change="beginTimeChange" placeholder="请选择 统计开始日期"></el-date-picker>
      </template>
      <template slot-scope="{disabled,size}" slot="endTimeSearch">
        <el-date-picker v-model="search.endTime" type="datetime" :editable="false" :clearable="false" default-time="23:59:59" value-format='yyyy-MM-dd HH:mm:ss' @change="endTimeChange" placeholder="请选择 统计结束日期"></el-date-picker>
      </template>
    </avue-crud>
    <div class="curd-foter">
      <div class="redFontBox">总交易金额：<span class="redFont">{{ exhibition(countData.totalRealAmount ) || 0.00 }}</span> 元</div>
      <div class="redFontBox">总交易笔数：<span class="redFont">{{ exhibition(countData.totalTradeCount) || 0.00 }}</span> 笔</div>
      <div class="redFontBox">总手续费：<span class="redFont">{{ exhibition(countData.totalAllFee) || 0.00 }}</span> 元</div>
      <div class="redFontBox">总结算金额：<span class="redFont">{{ exhibition(countData.totalIncome) || 0.00 }}</span> 元</div>
    </div>

    <el-dialog
      title="详情"
      :visible.sync="dialogVisible"
      append-to-body
      :before-close="handleClose"
      >
      <div>
        <div class="haruyuki-content">
          <el-row :gutter="20">
            <el-col :span="8">
              <span class="wordBreak">集团商户编号：{{detailObj.groupRpiNo}}</span>
            </el-col>
            <el-col :span="8">
              <span class="wordBreak">集团商户名称：{{detailObj.groupRpiName}}</span>
            </el-col>
            <el-col :span="8">
              <span class="wordBreak">商户编号：{{detailObj.rpiNo}}</span>
            </el-col>
            <el-col :span="8">
              <span class="wordBreak">商户注册名称：{{detailObj.mercAbbr}}</span>
            </el-col>
            <el-col :span="8">
              <span class="wordBreak">商户简称：{{detailObj.userShortName}}</span>
            </el-col>
             <el-col :span="8">
              <span class="wordBreak">统计日期：{{detailObj.dateStatistics}}</span>
            </el-col>
          </el-row>
        </div>
        <div>
          <div class="line">
            <div class="bgd-f6 line-time">支付类型</div>
            <div class="bgd-f6 line-time">订单笔数</div>
            <div class="bgd-f6 line-time">订单金额</div>
            <div class="bgd-f6 line-time">退款笔数</div>
            <div class="bgd-f6 line-time">退款金额</div>
            <div class="bgd-f6 line-time">总交易笔数</div>
            <div class="bgd-f6 line-time">总手续费金额</div>
            <div class="bgd-f6 line-time">结算金额</div>
          </div>
          <div v-if="detailObj.tradeList">
            <div class="line" v-for="(item,index) in detailObj.tradeList" :key="index">
              <div class="bgd-f6 line-time">{{exhibition(item.rpsCustTypeName)}}</div> <!-- 支付类型 -->
              <div class="bgd-f6 line-time">{{exhibition(item.tradeCount)}}</div> <!-- 订单笔数 -->
              <div class="bgd-f6 line-time">{{exhibition(item.tradeAmount)}}</div> <!-- 订单金额 -->
              <div class="bgd-f6 line-time">{{exhibition(item.refundCount)}}</div> <!-- 退款笔数 -->
              <div class="bgd-f6 line-time">{{exhibition(item.refundAmount)}}</div> <!-- 退款金额 -->
              <div class="bgd-f6 line-time">{{exhibition(item.totalCount)}}</div> <!-- 总交易笔数 -->
              <!-- <div class="bgd-f6 line-time">{{exhibition(item.totalAmount)}}</div> 总交易金额 -->
              <div class="bgd-f6 line-time">{{exhibition(item.totalFee)}}</div> <!-- 总手续费金额 -->
              <div class="bgd-f6 line-time">{{exhibition(item.totalSettlementAmount)}}</div> <!-- 结算金额 -->
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList,tradeList,tradeExport } from "@/api/rb-oem/dealManagement/dealCount";
import { getListCount } from "@/api/rb-oem/dealManagement/dealManagement";

import { mapGetters } from "vuex";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";
import { dateFormat } from "@/util/date";

export default {
  components: {
    selectPage
  },
  data() {
    return {
      form: {},
      query: {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      },
      search: {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      },
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel:'序号',
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText:'重置',
        column: [
          {
            label: "集团商户编号",
            prop: "groupRpiNo",
            type: "input",
            overHidden:true,
            searchLabel: "集团商户",
            search: true,
            searchOrder:1,
            minWidth: 140
          },
          {
            label: "集团商户名称",
            prop: "groupRpiName",
            type: "input",
            overHidden:true,
            minWidth: 180
          },
          {
            label: "商户编号",
            searchLabel: "商户",
            prop: "rpiNo",
            type: 'select',
            overHidden:true,
            width: 140,
            search: true,
            searchOrder:2
          },
          {
            label: "商户注册名称",
            prop: "mercAbbr",
            type: "input",
            overHidden:true,
            minWidth: 200
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            overHidden:true,
            width: 200
          },
          {
            label: "商户简称",
            prop: "userShortName",
            type: "input",
            overHidden:true,
            minWidth: 200
          },
          {
            label: "统计日期",
            prop: "dateStatistics",
            type: "input",
            overHidden:true,
            minWidth: 200
          },
          {
            label: "订单金额",
            prop: "tradeAmount",
            type: "input",
            overHidden:true,
            minWidth: 95
          },
          {
            label: "订单笔数",
            prop: "tradeCount",
            type: "input",
            overHidden:true,
            minWidth: 95
          },
          {
            label: "退款金额",
            prop: "refundAmount",
            type: "input",
            overHidden:true,
            minWidth: 95
          },
          {
            label: "退款笔数",
            prop: "refundCount",
            type: "input",
            overHidden:true,
            minWidth: 95
          },
          {
            label: "总交易笔数",
            prop: "totalCount",
            type: "input",
            overHidden:true,
            minWidth: 95
          },
          {
            label: "总手续费金额 ",
            prop: "totalFee",
            type: "input",
            overHidden:true,
            minWidth: 150
          },
          {
            label: "结算金额",
            prop: "totalSettlementAmount",
            type: "input",
            overHidden:true,
            minWidth: 95
          },
          {
            label: "统计开始日期",
            prop: "beginTime",
            search: true,
            hide: true,
            overHidden:true,
            display: false
          },
          {
            label: "统计结束日期",
            prop: "endTime",
            search: true,
            hide: true,
            overHidden:true,
            display: false
          },
          {
            label: "优选数据",
            prop: "isOpt",
            type: "select",
            dataType: "number",
            clearable:false,
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: false,
            dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
            hide:true,
            display:false,
            change: (item) => {
              if (item.value===1) {
                const isOptOrder = this.findObject(this.option.column, "isOptOrder");
                isOptOrder.search = true;
                isOptOrder.hide = false;
              }else{
                const isOptOrder = this.findObject(this.option.column, "isOptOrder");
                isOptOrder.search = false;
                isOptOrder.hide = true;
                this.query.isOptOrder = "";
                this.search.isOptOrder = "";
              }
            }
          },
          {
            label: "优选订单",
            prop: "isOptOrder",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: false,
            dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
            hide:true,
            display:false
          }
        ]
      },
      data: [],
      dialogVisible:false,
      countData: {},
      detailObj:{}
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.dealCount_view, false),
        exportBtn: this.vaildData(this.permission.dealCount_export, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1" || val == "0") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  created(){
    const isOpt = this.findObject(this.option.column, "isOpt");
    const isOptOrder = this.findObject(this.option.column, "isOptOrder");
    if(this.permission.opt_data){
      isOpt.search = true;
      isOptOrder.search = true;
      //isOpt.hide = false;
      isOptOrder.hide = false;
      this.query.isOpt = 1;
      this.search.isOpt = 1;
    }
  },
  methods: {
    handleClose(){
      this.dialogVisible = false;
    },
    /**
     * @func 详情
     * */
    handleDetail(row){
      let param = {
        rpiNo:row.rpiNo,
        beginTime: this.search.beginTime,
        endTime: this.search.endTime,
        isOpt:this.search.isOpt,
        isOptOrder:this.search.isOptOrder
      }

      tradeList(param).then((res) => {
        this.detailObj = res.data.data;
        this.dialogVisible = true;
      });
    },
    beginTimeChange() {
      if(this.search.endTime){
        if( new Date(this.search.beginTime).getFullYear() === new Date(this.search.endTime).getFullYear()){
          if(Date.parse(this.search.beginTime) > Date.parse(this.search.endTime)){
            this.$alert('统计开始日期不能大于结束日期', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
          }else if(Date.parse(this.search.beginTime) < Date.parse(this.search.endTime)-3600 * 1000 * 24 * 90){
            this.$alert('日期筛选间隔最大为 3个月', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
            this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
          }
        }else{
          if(Date.parse(this.search.beginTime) < Date.now() - 3600 * 1000 * 24 * 365 * 2){
            this.$alert('只能查询两年内的数据！', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
          }else{
            this.$alert('查询日期不能跨年', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
            this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
          }
        }
      }
    },
    endTimeChange() {
      if(this.search.beginTime){
        if( new Date(this.search.endTime).getFullYear() === new Date(this.search.beginTime).getFullYear()){
          if(Date.parse(this.search.endTime) < Date.parse(this.search.beginTime)){
            this.$alert('统计结束日期不能小于开始日期', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';

          }else if(Date.parse(this.search.beginTime)+3600 * 1000 * 24 * 90 < Date.parse(this.search.endTime)){
            this.$alert('日期筛选间隔最大为 3个月', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
          }
        }else{
          this.$alert('查询日期不能跨年', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
        }
      }
    },
    forInSearch(){
      for(let key in this.search){
        //console.log(key)
        if(this.search[key]){
          if(key.indexOf("$") == -1 ){
            this.query[key] = this.search[key]
          }
        }
      }
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      // this.query = {};
      this.query = {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      }
      this.search = {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      }
      if(this.permission.opt_data){
        this.query.isOpt = 1;
        this.search.isOpt = 1;
      }
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      /**
       * @func 统计
       * @desc 根据条件获取统计
       * */
      getListCount(Object.assign(params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      let params ={
        ...this.search,
        current:'-1',
        size:'-1'
      }
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        tradeExport(params).then((res) => {
          downloadFileExcel(res);
        },(error) => {
            window.console.log(error);
          }
        );
      })
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.haruyuki-content{
  padding:10px 10px 0 10px;
}
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
.tableItem{
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  height: 28px;
}
.el-divider--horizontal {
  margin: 4px 0 !important;
}

// stat---
.bgd-f6{
  background-color: #f6f6f6;
}
.line{
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ccc;
  // border-bottom: 1px solid #ccc;
  .line-time{
    width: 15%;
    text-align: center;
    border:1px solid #ccc;
    border-bottom: none;
    border-top: none;
    border-right: none;
    line-height: 30px;
  }
  .line-time:last-child{
    border-right: 1px solid #ccc;
  }
}
.line:last-child{
  border-bottom: 1px solid #ccc;
}

/deep/ .el-dialog__body{
  padding-top: 0;
}
// end---
</style>
